<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录网络调试工具</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 800px;
      margin: 0 auto;
      padding: 20px;
    }
    .container {
      border: 1px solid #ddd;
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 20px;
    }
    h1 { color: #333; }
    h2 { color: #555; margin-top: 20px; }
    .form-group {
      margin-bottom: 15px;
    }
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
    input {
      width: 100%;
      padding: 8px;
      box-sizing: border-box;
      border: 1px solid #ddd;
      border-radius: 4px;
    }
    button {
      background-color: #4CAF50;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 10px;
    }
    button:hover { background-color: #45a049; }
    .logs {
      background-color: #f5f5f5;
      padding: 15px;
      border-radius: 4px;
      height: 400px;
      overflow-y: auto;
      font-family: monospace;
      white-space: pre-wrap;
    }
    .log-entry {
      margin-bottom: 8px;
      border-bottom: 1px solid #eee;
      padding-bottom: 8px;
    }
    .timestamp { color: #888; }
    .success { color: #4CAF50; }
    .error { color: #f44336; }
    .info { color: #2196F3; }
    .debug { color: #666; }
  </style>
</head>
<body>
  <div class="container">
    <h1>登录网络调试工具</h1>
    <p>此工具用于直接测试登录请求的网络通信，跳过前端框架的干扰。</p>
    
    <h2>登录表单</h2>
    <div class="form-group">
      <label for="username">用户名</label>
      <input type="text" id="username" value="admin">
    </div>
    <div class="form-group">
      <label for="password">密码</label>
      <input type="password" id="password" value="admin">
    </div>
    
    <h2>测试选项</h2>
    <div class="form-group">
      <label for="url">请求URL</label>
      <select id="url">
        <option value="/api/auth/token">/api/auth/token (通过Vite代理)</option>
        <option value="http://localhost:8000/auth/token">http://localhost:8000/auth/token (直接后端API)</option>
        <option value="http://localhost:5176/api/auth/token">http://localhost:5176/api/auth/token (完整URL)</option>
      </select>
    </div>
    
    <button onclick="testFetch()">测试 Fetch API</button>
    <button onclick="testXMLHttpRequest()">测试 XMLHttpRequest</button>
    <button onclick="clearLogs()">清空日志</button>
    
    <h2>调试日志</h2>
    <div id="logs" class="logs"></div>
  </div>

  <script>
    // 日志级别枚举
    const LOG_LEVEL = {
      DEBUG: 'debug',
      INFO: 'info',
      SUCCESS: 'success',
      ERROR: 'error'
    };

    // 记录日志到界面
    function log(message, level = LOG_LEVEL.INFO) {
      const logsContainer = document.getElementById('logs');
      const timestamp = new Date().toLocaleTimeString();
      const logEntry = document.createElement('div');
      logEntry.className = `log-entry ${level}`;
      logEntry.innerHTML = `<span class="timestamp">[${timestamp}]</span> ${message}`;
      logsContainer.appendChild(logEntry);
      logsContainer.scrollTop = logsContainer.scrollHeight;
    }

    // 清空日志
    function clearLogs() {
      document.getElementById('logs').innerHTML = '';
    }

    // 获取表单数据
    function getFormData() {
      const username = document.getElementById('username').value;
      const password = document.getElementById('password').value;
      const url = document.getElementById('url').value;
      return { username, password, url };
    }

    // 创建FormData或URLSearchParams
    function createRequestData(username, password) {
      const params = new URLSearchParams();
      params.append('username', username);
      params.append('password', password);
      return params;
    }

    // 测试Fetch API
    async function testFetch() {
      try {
        const { username, password, url } = getFormData();
        const data = createRequestData(username, password);
        
        log('开始使用Fetch API测试登录请求', LOG_LEVEL.DEBUG);
        log(`请求URL: ${url}`, LOG_LEVEL.INFO);
        log(`请求参数: ${data.toString()}`, LOG_LEVEL.DEBUG);
        
        // 记录请求开始时间
        const startTime = performance.now();
        
        // 发送请求
        const response = await fetch(url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Accept': 'application/json'
          },
          body: data
        });
        
        // 记录请求结束时间和状态
        const endTime = performance.now();
        log(`请求完成，耗时: ${(endTime - startTime).toFixed(2)}ms，状态码: ${response.status} ${response.statusText}`, LOG_LEVEL.INFO);
        
        // 检查响应头
        const headers = {};
        for (const [key, value] of response.headers.entries()) {
          headers[key] = value;
        }
        log(`响应头: ${JSON.stringify(headers, null, 2)}`, LOG_LEVEL.DEBUG);
        
        // 尝试解析响应体
        try {
          const responseData = await response.json();
          log(`响应体(JSON格式): ${JSON.stringify(responseData, null, 2)}`, LOG_LEVEL.SUCCESS);
          
          // 检查是否包含必要字段
          if (responseData.access_token && responseData.user) {
            log('响应包含所有必要字段(access_token和user)', LOG_LEVEL.SUCCESS);
          } else {
            log('警告: 响应缺少必要字段!', LOG_LEVEL.ERROR);
          }
        } catch (jsonError) {
          // 如果不是JSON格式，尝试获取文本
          const textData = await response.text();
          log(`响应体(文本格式): ${textData}`, LOG_LEVEL.ERROR);
          log(`JSON解析错误: ${jsonError.message}`, LOG_LEVEL.ERROR);
        }
        
      } catch (error) {
        log(`请求异常: ${error.message}`, LOG_LEVEL.ERROR);
        log(`异常详情: ${JSON.stringify(error, null, 2)}`, LOG_LEVEL.ERROR);
      }
    }

    // 测试XMLHttpRequest
    function testXMLHttpRequest() {
      try {
        const { username, password, url } = getFormData();
        const data = createRequestData(username, password);
        
        log('开始使用XMLHttpRequest测试登录请求', LOG_LEVEL.DEBUG);
        log(`请求URL: ${url}`, LOG_LEVEL.INFO);
        log(`请求参数: ${data.toString()}`, LOG_LEVEL.DEBUG);
        
        const xhr = new XMLHttpRequest();
        
        // 记录请求开始时间
        const startTime = performance.now();
        
        xhr.open('POST', url, true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Accept', 'application/json');
        
        xhr.onreadystatechange = function() {
          if (xhr.readyState === XMLHttpRequest.HEADERS_RECEIVED) {
            // 记录响应头
            log(`收到响应头: ${xhr.getAllResponseHeaders()}`, LOG_LEVEL.DEBUG);
          } else if (xhr.readyState === XMLHttpRequest.DONE) {
            // 记录请求结束时间和状态
            const endTime = performance.now();
            log(`请求完成，耗时: ${(endTime - startTime).toFixed(2)}ms，状态码: ${xhr.status} ${xhr.statusText}`, LOG_LEVEL.INFO);
            
            // 检查响应体
            log(`响应体: ${xhr.responseText}`, LOG_LEVEL.SUCCESS);
            
            // 尝试解析JSON
            try {
              const responseData = JSON.parse(xhr.responseText);
              log(`响应体(JSON格式): ${JSON.stringify(responseData, null, 2)}`, LOG_LEVEL.SUCCESS);
              
              // 检查是否包含必要字段
              if (responseData.access_token && responseData.user) {
                log('响应包含所有必要字段(access_token和user)', LOG_LEVEL.SUCCESS);
              } else {
                log('警告: 响应缺少必要字段!', LOG_LEVEL.ERROR);
              }
            } catch (jsonError) {
              log(`JSON解析错误: ${jsonError.message}`, LOG_LEVEL.ERROR);
            }
          }
        };
        
        xhr.onerror = function(error) {
          log(`请求错误: ${error.type}`, LOG_LEVEL.ERROR);
        };
        
        xhr.ontimeout = function() {
          log('请求超时', LOG_LEVEL.ERROR);
        };
        
        // 发送请求
        xhr.send(data);
        
      } catch (error) {
        log(`请求异常: ${error.message}`, LOG_LEVEL.ERROR);
        log(`异常详情: ${JSON.stringify(error, null, 2)}`, LOG_LEVEL.ERROR);
      }
    }

    // 页面加载时自动运行一些基本检查
    window.onload = function() {
      log('网络调试工具已加载完成', LOG_LEVEL.SUCCESS);
      log('请输入用户名和密码，选择请求URL，然后点击测试按钮', LOG_LEVEL.INFO);
    };
  </script>
</body>
</html>